package com.wontube.smr.dao.bo;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.ibatis.session.SqlSession;

import com.wontube.core.dao.mybatis.QueryExample;
import com.wontube.smr.client.model.po.Movie;
import com.wontube.smr.client.model.po.MovieGenre;
import com.wontube.smr.dao.mapper.MovieGenreMapper;
import com.wontube.smr.dao.mapper.MovieMapper;
import com.wontube.smr.pub.DefaultDBHelper;


/**
 * MovieGenreDao 帮助类
 * 
 * @author hewc@wondershare.cn
 * 
 */
public class MovieGenreDao {
	private MovieGenreDao() {
	}

	/**
	 * 批量插入数据库
	 * 
	 * @param movies
	 */
	public static void saveOrUpdate(List<Movie> movies, String genre) {
		// 批量session
		SqlSession session = DefaultDBHelper.getBatchSqlSession();
		try {
			// 时间戳
			Date now = Calendar.getInstance().getTime();
			MovieMapper mapper = session.getMapper(MovieMapper.class);
			MovieGenreMapper genreMapper = session
					.getMapper(MovieGenreMapper.class);
			for (Movie movie : movies) {

				// itemUrl决定唯一性
				String itemUrl = movie.getItemUrl();
				QueryExample ex = new QueryExample();
				ex.or().addCriterion("item_url=", itemUrl);
				List<Movie> list = mapper.selectByExample(ex);
				if (list.size() > 0) {
					// update
					Movie po = list.get(0);
					String movieId = po.getId();

					QueryExample movieGenreEx = new QueryExample();
					movieGenreEx.or().addCriterion("movie_id=", movieId)
							.addCriterion("genre_name=", genre);
					List<MovieGenre> movieGenreList = genreMapper
							.selectByExample(movieGenreEx);
					if (movieGenreList.size() > 0) {
						MovieGenre movieGenre = movieGenreList.get(0);
						movieGenre.setGenreName(genre);
						genreMapper.updateByPrimaryKey(movieGenre);
					} else {
						MovieGenre movieGenre = new MovieGenre();
						movieGenre.setId(UUID.randomUUID().toString());
						movieGenre.setMovieId(movieId);
						movieGenre.setGenreName(genre);
						genreMapper.insert(movieGenre);
						
						String genreList = po.getGenre();
						if (genreList.length() == 0) {
							po.setGenre(genre);
						} else {
							po.setGenre(po.getGenre() + "," + genre);
						}
						po.setVersion(now);
						mapper.updateByPrimaryKey(po);
					}
					
				}
			}
			session.commit();
		} finally {
			session.close();
		}
	}
}
